//
//  PasswordViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/9/18.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "PasswordViewController.h"
#import "AllHeader.h"
#import "NSString+MD5.h"


//发送手机验证码
#define kSendPhoneCode @"http://arts1.dlab.com.cn/app/sendphonecode"

// 修改密码
#define findURL @"http://arts1.dlab.com.cn/app/findpassword"


@interface PasswordViewController ()<UITextViewDelegate>


// 重发验证码的剩余时间
@property (nonatomic, assign) NSInteger second;

//
@property (nonatomic, strong) NSTimer *timer;


@end

@implementation PasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self modifySubview];
    _second = 60;
}


// 开启NStimer
- (void)addTimer{
    _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

// 关闭NStimer
- (void)removeTimer{
    [_timer invalidate];
}

// 递减重新发送验证码剩余时间
- (void)changeTime{
    _second --;
    [_sendIdentifier setTitle:[NSString stringWithFormat:@"(%ld 秒)重发",(long)_second] forState:(UIControlStateSelected)];
    if (_second == 0) {
        _sendIdentifier.selected = NO;
        _sendIdentifier.userInteractionEnabled = YES;
        [self removeTimer];
        _second = 60;
    }
}



// 修饰子视图
- (void)modifySubview{
    // 给navitionview添加阴影
    [UIView viewShadowColor:_navigationview];
    
    // 设置请求按钮、发送验证码按钮圆角
    _requestButton.layer.cornerRadius = 4;
    _requestButton.layer.masksToBounds = YES;
    
    _sendIdentifier.layer.cornerRadius = 4;
    _sendIdentifier.layer.masksToBounds = YES;

    // 设置列表背景视图的阴影
    [UIView viewShadowColor:_whiteview];
    _whiteview.layer.cornerRadius = 4;
    
    // 设置textfield代理
    _phoneNum.delegate = self;
    _identifier.delegate = self;
    _nPassword.delegate = self;
    _rNPassword.delegate = self;
}


// 返回上一层
- (IBAction)back:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}



// 确认点击事件
- (IBAction)confirm:(UIButton *)sender {
    [self registerInfo];
}

#warning 需要进一步验证修改密码的网络请求是否完整
//判断输入信息是否完整
- (void)registerInfo
{
    if (_phoneNum.text.length == 0 || _identifier.text.length == 0 || _nPassword.text.length == 0 || _rNPassword.text.length == 0)
    {
        [MBProgressHUD show:@"输入信息不完整" icon:nil view:self.view];
    }
    else
    {
        if (_nPassword.text.length < 6)
        {
            [MBProgressHUD show:@"密码不能少于6位" icon:nil view:self.view];
        }
        else
        {
            [self requestVerifyPhoneCode];
        }
    }
}



// 更改密码请求
- (void)requestVerifyPhoneCode{
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    //MD5加密
    NSString *pwdResult = [NSString MD5WithString:_nPassword.text];
    NSString *rpwdResult = [NSString MD5WithString:_rNPassword.text];
    
    NSDictionary *pardic = @{@"phone":_phoneNum.text,@"password":pwdResult,@"rpassword":rpwdResult,@"phonecode":_identifier.text};
    
    [manage POST:findURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary * sender = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers) error:nil];
         int index = [sender[@"status"] intValue];
         NSString *statusStr = nil;
         switch (index)
         {
             case 1:
             {
                 statusStr = @"注册成功";
                 
//                 RegisterInfoController *registerInfo = [[RegisterInfoController alloc] init];
//                 [self.navigationController pushViewController:registerInfo animated:YES];
                 
             }
                 break;
             case 0:
                 statusStr = @"注册失败";
                 break;
             case -1:
                 statusStr = @"手机号码不符合规范";
                 break;
             case -2:
                 statusStr = @"验证码错误";
                 break;
             case -3:
                 statusStr = @"输错5次,该手机号不能注册";
                 break;
             case -4:
                 statusStr = @"验证码不正确";
                 break;
             case -5:
                 statusStr = @"输入信息不正确";
                 break;
             case -6:
                 statusStr = @"两次输入的密码不相同";
                 break;
             case -7:
                 statusStr = @"密码不能少于6位字符";
                 break;
             case -8:
                 statusStr = @"该手机号已被注册";
                 break;
                 
             default:
                 break;
         }
         
         [MBProgressHUD show:statusStr icon:nil view:self.view];
     }
         failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         // 请求失败的时候调用调用这个block
         [MBProgressHUD show:@"当前网络不可用" icon:nil view:self.view];
     }];
    
}


// 发送验证码
- (IBAction)sendIdentifierCode:(id)sender {
    
    //  验证码按钮
    UIButton *codeBTN = (UIButton *)sender;
    codeBTN.selected = !codeBTN.isSelected;
    
    if (codeBTN.selected) {
        // 被点击之后，更换显示文字
        [codeBTN setTitle:[NSString stringWithFormat:@"(%ld 秒)重发",(long)_second] forState:(UIControlStateSelected)];
        [self addTimer];
        codeBTN.userInteractionEnabled = NO;
        [self requestSendPhoneCode];
    } else {
        if (_second == 0) {
            codeBTN.selected = !codeBTN.selected;
            codeBTN.userInteractionEnabled = YES;
            [self removeTimer];
        }
    }
}

// 验证码请求
- (void)requestSendPhoneCode{
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    NSDictionary *pardic = nil;
    if ( _phoneNum.text.length < 11) {
        [MBProgressHUD show:@"请重新输入电话号码" icon:nil view:self.view];
    } else {
    pardic = @{@"phone":_phoneNum.text};
    }
    [manage POST:kSendPhoneCode parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSString * str = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             
             // 请求成功的时候调用这个block
             NSLog(@"验证码请求--%@", str);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}


// 服务与条款
- (IBAction)service:(id)sender {
    
    
    
    
    
}



// 触摸空白区域取消编辑
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

// 键盘的return键 切换下一行
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == _phoneNum) {
        [_identifier becomeFirstResponder];
    } else if (textField == _identifier ) {
        [_nPassword becomeFirstResponder];
    } else if (textField == _nPassword ) {
        [_rNPassword becomeFirstResponder];
    } else {
     [self.view endEditing:YES];
    }
    return YES;
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
